﻿using LunarSF.SHomeWorkshop.LunarMarkdownEditor.CustomWebBrowser;
using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// SearchWindow.xaml 的交互逻辑
    /// </summary>
    public partial class WebSearchWindow :MetroWindow
    {
        public WebSearchWindow()
        {
            InitializeComponent();
            //阻止片段预览WebBrowser弹出新IE（或其它浏览器）窗口
            var webBrowserHelper = new WebBrowserHelper(webBrowser);
            HelperRegistery.SetHelperInstance(this, webBrowserHelper);
            webBrowserHelper.NewWindow += WebBrowserOnNewWindow;
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            
            //强制 WebBrowser 在内部打开链接（而不是弹出其它浏览器）
            var helperInstance = HelperRegistery.GetHelperInstance(this);
            if (helperInstance != null)
            {
                helperInstance.NewWindow -= WebBrowserOnNewWindow;
                helperInstance.Disconnect();
            }
            // 下面这行会导致关闭程序时会出现异常。
            // this.Owner.Activate();
        }

        private void WebBrowserOnNewWindow(object sender, CancelEventArgs e)
        {
            dynamic browser = sender;
            dynamic activeElement = browser.Document.activeElement;
            var link = activeElement.ToString();
            //默认是在新窗口中打开，如果要在内部打开，改变当前browser的Source就行了
            webBrowser.Source = new Uri(link);
            e.Cancel = true;
        }

        private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
            // 下面这行会导致关闭程序时会出现异常。
            // this.Owner.Activate();
        }

        //一旦页面出错，弹出错误框，这个方法会导致无法关闭搜索窗口，难用得很。
        //private void MetroWindow_Deactivated(object sender, EventArgs e)
        //{
        //    this.WindowState = WindowState.Minimized;
        //}
    }
}
